package org.jeecg.common.util;

import cn.hutool.core.util.RandomUtil;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.jeecg.common.constant.YsReptileConstant;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 文件跑龙套
 *
 * @author Yafei Song
 * @date 2022/09/29
 */
public class ReFileUtils {


    /**
     * 得到img
     *
     * @param imgSrc 图片路径
     * @return {@link String}
     */
    public static synchronized String getImg(String imgSrc) {
        InputStream is = null;
        OutputStream os = null;
        try {
            URL url = new URL(imgSrc);
            is = url.openStream();
            String fileName = YsReptileConstant.IMG_PATH + RandomUtil.randomNumbers(6) + YsReptileConstant.EXTJPG;
            os = new FileOutputStream(fileName);
            int data = 0;
            while ((data = is.read()) != -1) {
                os.write(data);
                os.flush();
            }
            return fileName;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 创建文件项
     *
     * @param filePath 文件路径
     * @param fileName 文件名称
     * @return {@link FileItem}
     */
    public static FileItem createFileItem(String filePath, String fileName){
        String fieldName = "file";
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", false,fileName);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try (FileInputStream fis = new FileInputStream(newfile);
             OutputStream os = item.getOutputStream()) {
            while ((bytesRead = fis.read(buffer, 0, 8192))!= -1)
            {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }

}
